package com.inplaceedit.client.ui.contact;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.editor.client.EditorDelegate;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;
import com.core.gwt.ui.client.HyperLabel;
import com.core.gwt.ui.client.HyperString;
import com.inplaceedit.shared.dto.CompanyDto;
import com.inplaceedit.shared.dto.ContactDto;

public class ContactNameDisplayView extends Composite implements
		ContactNameDisplay {

	interface Binder extends UiBinder<Widget, ContactNameDisplayView> {
	}

	private static Binder uiBinder = GWT.create(Binder.class);

	@UiField
	HyperLabel line1;
	@UiField
	HyperLabel line2;

	private Handler handler;
	private ContactDto value;

	public ContactNameDisplayView() {
		initWidget(uiBinder.createAndBindUi(this));
	}

	@Override
	public void flush() {
	}

	@Override
	public void onPropertyChange(final String... paths) {
	}

	@Override
	public void setDelegate(final EditorDelegate<ContactDto> delegate) {
	}

	@Override
	public void setHandler(final Handler handler) {
		this.handler = handler;
	}

	@Override
	public void setValue(final ContactDto value) {
		this.value = value;
		update();
	}

	private void update() {
		line1.setText("");
		line2.setText("");
		if (value != null) {
			updateLine1();
			updateLine2();
		}
	}

	private void updateLine1() {
		final StringBuilder sb = new StringBuilder();
		if (value.getFirstName() != null && value.getFirstName().length() > 0) {
			sb.append(value.getFirstName());
		}
		if (value.getLastName() != null && value.getLastName().length() > 0) {
			if (sb.length() > 0) {
				sb.append(" ");
			}
			sb.append(value.getLastName());
		}
		line1.setText(sb.toString());
	}

	private void updateLine2() {
		final List<HyperString> args = new ArrayList<HyperString>();
		int argIndex = 0;
		final StringBuilder sb = new StringBuilder();
		if (value.getTitle() != null && value.getTitle().length() > 0) {
			sb.append(value.getTitle());
		}
		if (value.getCompany() != null) {
			if (sb.length() > 0) {
				sb.append(" at ");
			}
			sb.append("{");
			sb.append(argIndex);
			sb.append("}");

			final CompanyDto company = value.getCompany();
			final HyperString arg = (handler != null) ? new HyperString(
					company.getName(), handler.getHistoryToken(company))
					: new HyperString(company.getName());
			args.add(arg);
			argIndex++;
		}
		if (args.size() > 0) {
			HyperString[] argArray = new HyperString[args.size()];
			argArray = args.toArray(argArray);
			line2.setText(sb.toString(), argArray);
		} else {
			line2.setText(sb.toString());
		}
	}
}
